import asyncio
from datetime import datetime
import pytz
from app import app
from config import GROUP_ID, GROUP_NAME, db_info
from pyrogram.errors import PeerIdInvalid
from pyrogram.types.messages_and_media import Message
from app.libs.logs import logger


async def delete_message(message_del, sleep_time=35):
    await asyncio.sleep(sleep_time)
    await message_del.delete()


async def get_nowtime(Typecode):
    utc_plus_8 = pytz.timezone("Asia/Shanghai")  #'Asia/Shanghai' 是 UTC+8 时区
    nowtime_utc_plus_8 = datetime.now(utc_plus_8)
    result = ""
    if Typecode == "now":
        result = nowtime_utc_plus_8
    elif Typecode == "date":
        result = nowtime_utc_plus_8.date()
    elif Typecode == "time":
        result = nowtime_utc_plus_8.time()
    elif Typecode == "year":
        result = nowtime_utc_plus_8.year
    elif Typecode == "month":
        result = nowtime_utc_plus_8.month
    elif Typecode == "day":
        result = nowtime_utc_plus_8.day
    elif Typecode == "min":
        result = nowtime_utc_plus_8.minute
    elif Typecode == "sec":
        result = nowtime_utc_plus_8.second
    else:
        print("Invalid operator")
        result = None
    return result


####################根据TGID查询用户信息##########################################
async def get_user_info(tgid):

    try:
        user_entity = await app.get_users(tgid)

        result = 1
        logger.info(f"User查询成功: ID: {tgid} userifo:{user_entity}")

    except PeerIdInvalid:
        logger.debug(f"一次查询账户不存在: ID: {tgid} userifo:{PeerIdInvalid}")
        logger.info(f"一次查询账户不存在: ID: {tgid} userifo:{PeerIdInvalid}")
        try:
            user_entity = await app.get_users(tgid)
            result = 1
            logger.info(f"二次查询User查询成功: ID: {tgid} userifo:{user_entity}")
        except PeerIdInvalid:
            user_entity = PeerIdInvalid
            result = 2
            logger.debug(f"二次查询账户不存在: ID: {tgid} userifo:{user_entity}")
    except Exception as e:
        user_entity = f"An unexpected error occurred: {e}"
        result = 3
    return user_entity, result


####################查询数组内所有ID的 username##########################################
async def get_usertoarray(sorted_array):
    new_sorted_array = []
    logger.info(f"需要查询的uesrname的ID: {sorted_array}")
    for i in range(len(sorted_array)):
        second_first_element = sorted_array[i][0]
        result_TGID = second_first_element[4:]
        if result_TGID.isdigit():
            user_entity, result_code = await get_user_info(int(result_TGID))

            if result_code == 1:
                if user_entity.first_name:
                    if user_entity.last_name:
                        tgname = user_entity.first_name + " " + user_entity.last_name
                    else:
                        tgname = user_entity.first_name
                else:
                    tgname = " "
            elif result_code == 2:
                tgname = user_entity
        else:
            tgname = second_first_element

        new_sorted_array.append([tgname] + sorted_array[i][1:])
    return new_sorted_array


async def forwardmessage(chat_id, target_message: Message):

    try:
        await target_message.forward(chat_id)

    except Exception as e:
        logger.error(f"首次发送失败,再次尝试: error: {e}")
        try:
            chat = await app.get_chat(chat_id)
            if chat:
                logger.info(f"获取群组成功,再次尝试")
                await target_message.forward(chat_id)
            else:
                logger.info(f"群组不存在")
                return
        except Exception as e:
            logger.error(f"Initial send failed with error: {e}")


async def sendmessage(chat_id, target_message):
    try:
        send_result = await app.send_message(chat_id, target_message)
        return send_result
    except Exception as e:
        logger.error(f"首次发送失败,再次尝试: error: {e}")
        try:
            chat = await app.get_chat(chat_id)
            if chat:
                logger.info(f"获取群组成功,再次尝试")
                send_result = await app.send_message(chat_id, target_message)
                return send_result
            else:
                logger.info(f"群组不存在")
                return None
        except Exception as e:
            logger.error(f"Initial send failed with error: {e}")
            return None


#######################################################
async def get_group_name(fend_group_id):
    # 检查是否存在对应的 group_id
    if fend_group_id in GROUP_ID.values():
        # 在 GROUP_ID 字典中查找对应的键
        for key, value in GROUP_ID.items():
            if value == fend_group_id:
                if key in GROUP_NAME:
                    return GROUP_NAME[key]
    # 如果没有找到匹配的 group_id，则返回空字符串或其他适当的值
    return None


"""
async def group_Antisleep():
    send_result1 = await app.send_message(chat_id=GROUP_ID["PRIVATE_ID"],text=f"{randint(0,10000)}")
    await delete_message(send_result1,1) 
    logger.info(f"个人群组防休眠任务执行完成")

scheduler.add_job(group_Antisleep,'cron',minute='*/15',id='Antisleep') 
"""
